package com.chilly.netty.websocket.action.connectMonitor;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * websocket 实例
 * https://www.bilibili.com/video/BV1Q5411a7Hy?p=6
 * <p>
 * 通用handler，处理 I/O事件
 * Created by Chilly Cui on 2020/12/25.
 */
@ChannelHandler.Sharable //注解
public class HandlerClientMonitorEvent extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     * 处理收到的消息
     *
     * @param ctx
     * @param msgByteBuf
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msgByteBuf) throws Exception {
        System.out.println("收到的消息：" + msgByteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 处理I/O事件的异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String strDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss SSS"));
        ctx.writeAndFlush(Unpooled.copiedBuffer("这是客户端在 Active 中反馈的信息 " + strDateTime, CharsetUtil.UTF_8));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("服务端：" + incoming + "掉线");
    }
}
